
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="gopsutil获取服务器的信息">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>gopsutil获取服务器的信息 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        gopsutil获取服务器的信息
      </h1>
      <span>
        
        <time class="time" datetime="2019-12-08T16:00:00.000Z">
        2019-12-09
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p><code>psutil</code>是一个跨平台进程和系统监控的Python库，而<code>gopsutil</code>是其Go语言版本的实现。本文介绍了它的基本使用。</p>
<p>Go语言部署简单、性能好的特点非常适合做一些诸如采集系统信息和监控的服务，本文介绍的<a href="https://github.com/shirou/gopsutil" target="_blank" rel="noopener">gopsutil</a>库是知名Python库：<a href="https://github.com/giampaolo/psutil" target="_blank" rel="noopener">psutil</a>的一个Go语言版本的实现。</p>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">go get github.com/shirou/gopsutil</span><br></pre></td></tr></table></figure>

<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><h3 id="CPU"><a href="#CPU" class="headerlink" title="CPU"></a>CPU</h3><p>采集CPU相关信息。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"github.com/shirou/gopsutil/cpu"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// cpu info</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getCpuInfo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	cpuInfos, err := cpu.Info()</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"get cpu info failed, err:%v"</span>, err)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> _, ci := <span class="keyword">range</span> cpuInfos &#123;</span><br><span class="line">		fmt.Println(ci)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// CPU使用率</span></span><br><span class="line">	<span class="keyword">for</span> &#123;</span><br><span class="line">		percent, _ := cpu.Percent(time.Second, <span class="literal">false</span>)</span><br><span class="line">		fmt.Printf(<span class="string">"cpu percent:%v\n"</span>, percent)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>获取CPU负载信息：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"github.com/shirou/gopsutil/load"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getCpuLoad</span><span class="params">()</span></span> &#123;</span><br><span class="line">	info, _ := load.Avg()</span><br><span class="line">	fmt.Printf(<span class="string">"%v\n"</span>, info)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Memory"><a href="#Memory" class="headerlink" title="Memory"></a>Memory</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"github.com/shirou/gopsutil/mem"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// mem info</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getMemInfo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	memInfo, _ := mem.VirtualMemory()</span><br><span class="line">	fmt.Printf(<span class="string">"mem info:%v\n"</span>, memInfo)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Host"><a href="#Host" class="headerlink" title="Host"></a>Host</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"github.com/shirou/gopsutil/host"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// host info</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getHostInfo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	hInfo, _ := host.Info()</span><br><span class="line">	fmt.Printf(<span class="string">"host info:%v uptime:%v boottime:%v\n"</span>, hInfo, hInfo.Uptime, hInfo.BootTime)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Disk"><a href="#Disk" class="headerlink" title="Disk"></a>Disk</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"github.com/shirou/gopsutil/disk"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// disk info</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getDiskInfo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	parts, err := disk.Partitions(<span class="literal">true</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"get Partitions failed, err:%v\n"</span>, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> _, part := <span class="keyword">range</span> parts &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"part:%v\n"</span>, part.String())</span><br><span class="line">		diskInfo, _ := disk.Usage(part.Mountpoint)</span><br><span class="line">		fmt.Printf(<span class="string">"disk info:used:%v free:%v\n"</span>, diskInfo.UsedPercent, diskInfo.Free)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	ioStat, _ := disk.IOCounters()</span><br><span class="line">	<span class="keyword">for</span> k, v := <span class="keyword">range</span> ioStat &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"%v:%v\n"</span>, k, v)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="net-IO"><a href="#net-IO" class="headerlink" title="net IO"></a>net IO</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"github.com/shirou/gopsutil/net"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getNetInfo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	info, _ := net.IOCounters(<span class="literal">true</span>)</span><br><span class="line">	<span class="keyword">for</span> index, v := <span class="keyword">range</span> info &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"%v:%v send:%v recv:%v\n"</span>, index, v, v.BytesSent, v.BytesRecv)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="net"><a href="#net" class="headerlink" title="net"></a>net</h2><h3 id="获取本机IP的两种方式"><a href="#获取本机IP的两种方式" class="headerlink" title="获取本机IP的两种方式"></a>获取本机IP的两种方式</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GetLocalIP</span><span class="params">()</span> <span class="params">(ip <span class="keyword">string</span>, err error)</span></span> &#123;</span><br><span class="line">	addrs, err := net.InterfaceAddrs()</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> _, addr := <span class="keyword">range</span> addrs &#123;</span><br><span class="line">		ipAddr, ok := addr.(*net.IPNet)</span><br><span class="line">		<span class="keyword">if</span> !ok &#123;</span><br><span class="line">			<span class="keyword">continue</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> ipAddr.IP.IsLoopback() &#123;</span><br><span class="line">			<span class="keyword">continue</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> !ipAddr.IP.IsGlobalUnicast() &#123;</span><br><span class="line">			<span class="keyword">continue</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> ipAddr.IP.String(), <span class="literal">nil</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>或：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Get preferred outbound ip of this machine</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GetOutboundIP</span><span class="params">()</span> <span class="title">string</span></span> &#123;</span><br><span class="line">	conn, err := net.Dial(<span class="string">"udp"</span>, <span class="string">"8.8.8.8:80"</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> conn.Close()</span><br><span class="line"></span><br><span class="line">	localAddr := conn.LocalAddr().(*net.UDPAddr)</span><br><span class="line">	fmt.Println(localAddr.String())</span><br><span class="line">	<span class="keyword">return</span> localAddr.IP.String()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#安装"><span class="toc-text">安装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#使用"><span class="toc-text">使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#CPU"><span class="toc-text">CPU</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Memory"><span class="toc-text">Memory</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Host"><span class="toc-text">Host</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Disk"><span class="toc-text">Disk</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#net-IO"><span class="toc-text">net IO</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#net"><span class="toc-text">net</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#获取本机IP的两种方式"><span class="toc-text">获取本机IP的两种方式</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2019/12/09/Django的auth模块/" rel="next" title="Django 用户认证（Auth）组件">
          Django 用户认证（Auth）组件
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2019/12/12/微服务的架构演变/" rel="prev" title="微服务架构演进">
            微服务架构演进
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
